<?php
/**
 * Created by PhpStorm.
 * User: bg
 * Date: 2017/9/30 0030
 * Time: 上午 9:14
 */
namespace app\api\controller;

use think\Exception;
use think\Validate;
use think\Request;
use think\Db;
use think\Cache;
use app\common\model\Contract;
use app\common\model\ContractEquipment;
use app\common\model\RenewRecord;
use app\common\model\ForCoreRecord;
use app\common\model\NewRecord;
use app\common\model\DisassembleRecord;
use app\common\model\ShiftRecord;
use app\common\model\RepairRecord;
use app\common\model\RenewRepairRecord;
use app\common\model\ForCoreRepairRecord;
use app\common\model\WorkOrderRemarks;
use app\common\model\WorkOrderLog;


//客户端
class Customer extends RestBase{

    protected $customerDao;
    protected $contractDao;
    protected $contractEquipmentDao;
    protected $cACenterDao;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->customerDao =  Db::name('customer');
        $this->contractDao =  new Contract();
        $this->contractEquipmentDao =  new ContractEquipment();
    }

    //获取验证码
    public function getcode(){
        $code = rand(100000,900000);
        cache('code',$code);
        $this->success('成功',$code);
    }
    public function sendsms(){
        $validate = new Validate([
            'telphone' => 'require',
            'code' => 'require',
        ]);
        $validate->message([
            'telphone.require' => '请输入手机号',
            'code.require' => '请输入验证码',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $code = cache('code');
        if(!isset($data['code']) || $code != $data['code']){
            $this->error('验证码错误');
        }
        cache('code',null);
        $fwhere['telphone'] = $data['telphone'];
        $fwhere['is_delete'] = 0;
        $customerInfo = $this->customerDao->where($fwhere)->find();
        if(!$customerInfo){
            $this->error('电话号码不存在');
        }
        $scode = rand(1000,9000);
        cache($data['telphone'],$scode);
        $ret = sendSms($data['telphone'],$scode);
        if($ret==1){
            $this->success('验证码发送成功');
        }else{
            $this->error('验证码发送失败');
        }

    }

    //查询客户信息获取合同
    public function queryCustomer(){
        $validate = new Validate([
            'stype' => 'require',
        ]);
        $validate->message([
            'stype.require' => '请输入查询条件',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $userQuery = $this->customerDao;
        $cWhere['account_status']=1;
        if($data['stype']==1){
            if(!isset($data['id_card']) || !trim($data['id_card'])){
                $this->error('身份证不能为空');
            }
            if(!isset($data['code']) || $data['code']!=cache('code')){
                $this->error('验证码错误');
            }
            cache('code',null);
            $cWhere['id_card']=$data['id_card'];
            $userQuery = $userQuery->where($cWhere);
        }else{
            if(!isset($data['telphone']) || !trim($data['telphone'])){
                $this->error('电话不能为空');
            }
            if(!isset($data['code']) || $data['code']!=cache($data['telphone'])){
                $this->error('短信验证码错误');
            }
            cache($data['telphone'],null);
            $cWhere['telphone']=$data['telphone'];
            $userQuery = $userQuery->where($cWhere);
        }
        $userQuery->field('user_id,telphone,username');
        $customerInfo = $userQuery->find();
        if(!$customerInfo){
            $this->error('客户不存在');
        }
        $cwhere = array('user_id'=>$customerInfo['user_id'],'is_delete'=>0,'contract_status'=>1);
        $cfield = "contract_id,user_id,contract_no,contact_person,installed_time,province,city,area,address";
        $customerInfo['telphone'] = msubstr($customerInfo['telphone'],0,3,'utf-8','****').msubstr($customerInfo['telphone'],7,4,'utf-8','');
        $contractList['userinfo'] = $customerInfo;
        $clist = $this->contractDao->selectData($cwhere,$cfield);
        foreach ($clist as $key=>&$val){
            $val['installed_time'] = date('Y-m-d',  $val['installed_time']);
            $address = $val['province'].$val['city'].$val['area'].$val['address'];
            $val['address'] = msubstr($address,0,13);
            $val['contact_person'] = msubstr($val['contact_person'],0,1);
        }
        $contractList['list'] = $clist;
        $this->success('成功',$contractList);
    }

    //根据合同ID获取设备
    public function getEquipments(){
        $validate = new Validate([
            'coid' => 'require',
        ]);
        $validate->message([
            'coid.require' => '请填写必要参数!',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $cewhere=array('contract_id'=>$data['coid'],'state'=>1);
        $cefield = 'id,contract_id,equipments_id,equipments_number,equipments_address';
        $ceList = $this->contractEquipmentDao->getLists($cewhere,$cefield);
        if(!$ceList){
            $this->error('没有绑定设备');
        }
        foreach ($ceList as $key=>&$val){
            $val['equipments_address'] = msubstr($val['equipments_address'],0,10);
        }
        $this->success('成功',$ceList);
    }

    //用户提交工单
    public function  subOrder(){
        $validate = new Validate([
            'user_id' => 'require',
            'business_id' => 'require',
            'contract_id' => 'require',
            'equipmentr_id' => 'require',
            'contacts' => 'require',
            'contact_number' => 'require',
        ]);
        $validate->message([
            'user_id.require' => '参数异常!',
            'business_id.require' => '请选择保修类型!',
            'contract_id.require' => '请选择合同!',
            'equipmentr_id.require' => '请选择设备!',
            'contacts.require' => '请输入联系人!',
            'contact_number.require' => '请输入联系人电话!',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //查找客户
        $cufWhere['user_id'] = $data['user_id'];
        $cufWhere['is_delete'] = 0;
        $cuInfo = $this->customerDao->where($cufWhere)->find();
        if(!$cuInfo){
            $this->error('您的信息异常!');
        }
        //查找合同属于行政区域
        $cofWhere['contract_id'] = $data['contract_id'];
        $cofWhere['is_delete'] = 0;
        $coInfo = db('contract')->where($cofWhere)->find();
        if(!$coInfo){
            $this->error('合同信息异常!');
        }
        if($coInfo['is_Expire']==1){
            //$this->error('合同到期,请续费!');
        }
        $administrative_id = $coInfo['administrative_id'];
        $operation_id = $coInfo['operation_id'];
        //查找设备信息
        $conEqInfo = db('contract_equipment')->where(array('id'=>$data['equipmentr_id'],'is_delete'=>0))->find();
        if(!$conEqInfo){
            $this->error('设备不存在!');
        }
        if(!isset($data['remarks'])){
            $data['remarks'] = ' ';
        }
        if($data['business_id'] == 5){
            if(!isset($data['move_address']) || !trim($data['move_address'])){
                $this->error('移机地址不能为空');
            }
        }
        Db::startTrans();
        try{
            $oiData['user_id'] = $data['user_id'];
            $oiData['order_number'] = workOrderNumber();
            $oiData['contract_id'] = $data['contract_id'];
            $oiData['administrative_id'] = $administrative_id;
            $oiData['operation_id'] = $operation_id;
            $oiData['business_id'] = $data['business_id'];
            $oiData['isuser'] = 1;
            $oiData['service_address'] = $coInfo['province'].$coInfo['city'].$coInfo['area'].$conEqInfo['equipments_address'];
            $oiData['work_order_status'] = 2;
            $oiData['order_time'] = time();
            $oiData['update_time'] = time();
            $oiData['remarks'] = $data['remarks'];
            $oiData['contacts'] = $data['contacts'];
            $oiData['reception_user'] = 1;
            $oiData['contact_number'] = $data['contact_number'];
            $oiData['move_address'] = isset($data['move_address'])?$data['move_address']:'';
            $woid = db('work_order')->insertGetId($oiData);

            // 获取工单类型
            $workType = config('workorder_type');
            // 声明一个空数组用来装工单日志表数据
            $workDataLog=[];
            $workDataLog['work_order_id'] = $woid;     // 工单id
            $workDataLog['create_work_time'] = time();    // 订单创建时间
            $workDataLog['operating_time'] = time();      // 操作时间
            $workDataLog['operating_type'] = -1;           // 操作类型  0为前台确认
            $workDataLog['operating_status'] = 2;         // 操作状态为1  已处理
            $workDataLog['do_id'] = 0;                // 操作人id
            $workNum=db('work_order')->where(['work_order_id'=>$woid])->value('order_number');
            $workDataLog['remarks'] = '客户添加工单类型【'.$workType[$data['business_id']].'】工单号为【'.$workNum.'】';  // 备注信息
            // 实例化工单日志表
            $workLogModel = new WorkOrderLog();
            // 调用add方法增加工单日志数据
            $workLogModel->add($workDataLog);

            //插入工单设备关联表
            $woeqData['work_order_id'] = $woid;
            $woeqData['contract_equipment_id'] = $data['equipmentr_id'];
            db('work_equipment')->insert($woeqData);



            // 业务类型记录表
            $record['work_order_id'] = $woid;                 // 工单id
            $record['user_id'] = $data['user_id'];               // 客户id
            $record['repair_id'] = 0;                            // 新增工单没有工程人员
            $record['equipment_id'] = $data['equipmentr_id'];    // 合同设备关联id
            $record['remarks'] = '客户工单'; // 备注信息
            $record['contract_id'] = $oiData['contract_id']; // 备注信息

            // 根据新增工单业务类型增加对应记录表数据
            // 表示增加续费工单
            if ($data['business_id'] == 1) {
                $record['renew_record_time'] = time();
                $renewModel = new RenewRecord();
                $recordData = $renewModel->insertOne($record);
            }
            // 表示增加换芯工单
            if ($data['business_id'] == 2){
                $record['for_core_record_time'] = time();
                $forcorerecordModel = new ForCoreRecord();
                $recordData = $forcorerecordModel->insertOne($record);
            }
            // 表示增加新装工单
            if ($data['business_id'] == 3){
                $record['new_record_time'] = time();
                $newrecordModel = new NewRecord();
                $recordData = $newrecordModel->add($record);
            }
            // 表示增加拆机工单
            if ($data['business_id'] == 4){
                $record['disassemble_record_time'] = time();
                $disassembleModel = new DisassembleRecord();
                $recordData = $disassembleModel->add($record);
            }
            // 表示增移机工单
            if ($data['business_id'] == 5){
                $record['shift_recordd_time'] = time();
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->insertOne($record);
            }
            // 表示增移机拆工单
            if ($data['business_id'] == 9){
                $record['shift_recordd_time'] = time();
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->insertOne($record);
            }
            // 表示增移机装工单
            if ($data['business_id'] == 10){
                $record['shift_recordd_time'] = time();
                $shiftModel = new ShiftRecord();
                $recordData = $shiftModel->insertOne($record);
            }
            // 表示维修工单
            if ($data['business_id'] == 6){
                $record['repair_record_time'] = time();

                $repairModel = new RepairRecord();
                $recordData = $repairModel->add($record);
            }
            // 表示增续费+维修工单
            if ($data['business_id'] == 7){
                $record['renew_repair_record_time'] = time();
                $renewrepairModel = new RenewRepairRecord();
                $recordData = $renewrepairModel->insertOne($record);
            }
            // 表示增换芯+维修工单
            if ($data['business_id'] == 8){
                $record['for_core_repair_record_time'] = time();
                $forcorerepairModel = new ForCoreRepairRecord();
                $recordData = $forcorerepairModel->insertOne($record);
            }


            // 增加工单备注关联表
            $workRemarksData = [];
            $workRemarksData['u_id'] = $data['user_id'];                                                    // 操作人id
            $workRemarksData['username'] = $cuInfo['username'];                                                       // 操作人姓名
            $workRemarksData['operating_time'] = time();                                                    // 操作时间
            $workRemarksData['work_order_id'] = $woid;                                                   // 工单id
            $workRemarksData['remarks'] = $data['remarks'] ? $data['remarks'] : '客户新增工单';                 // 备注信息
            // 实例化工单备注关联表
            $workRemarksModel = new WorkOrderRemarks();
            // 调用add方法增加工单备注关联表数据
            $remarksData = $workRemarksModel->add($workRemarksData);
            Db::commit();
            $this->success('提交成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error('提交失败');
        }

    }

}
